<?php
/**
 * Description: 获取评价列表
 * User: devforma
 * Date: 16/1/4
 * Time: 14:02
 */

class GetRateList implements iController {

    const PERPAGE_COUNT = 15;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;
        if (empty($queryArgs['course_id']) && empty($queryArgs['class_id']) && empty($queryArgs['lector_id']))
            return genOutput(1000);

        if (empty($queryArgs['page']) || !filter_var($queryArgs['page'], FILTER_VALIDATE_INT) || $queryArgs['page'] < 1)
            return genOutput(1000);

        $uStatus = validateUser($queryArgs);

        if (!empty($queryArgs['course_id'])) {
            $classId = $cmsdb->getVar("SELECT `class_id` FROM `relationship_live_class_and_course` WHERE `course_id`=:cid LIMIT 1",
                array(':cid' => $queryArgs['course_id']));
            $data = $this->getRateByClass($classId, $uStatus === 1 ? $queryArgs['user_id'] : 0, $queryArgs['page']);

        } elseif (!empty($queryArgs['class_id'])) {
            $data = $this->getRateByClass($queryArgs['class_id'], $uStatus === 1 ? $queryArgs['user_id'] : 0,
                $queryArgs['page']);

        } elseif (!empty($queryArgs['lector_id'])) {
            $data = $this->getRateByLector($queryArgs['lector_id'], $queryArgs['page']);

        } else {
            return genOutput(1000);
        }

        return genOutput(1, $data);
    }


    private function getRateByLector($lectorId, $page = 1) {
        global $cmsdb, $uddb;

        $offset = ($page - 1) * self::PERPAGE_COUNT;

        $sql = "SELECT `id`, `course_id`, `class_id`, `user_id`, `grade_score`, `grade_time`, `comment`, `available`, `is_openclass` FROM `data_liveclass_grade`
        WHERE `lector_id`=:tid AND `grade_score`!=0 AND `available`=1 ORDER BY `id` DESC LIMIT {$offset}, ".self::PERPAGE_COUNT;
        $rates = $cmsdb->getResults($sql, array(':tid' => $lectorId));

        $data = array(
            'status' => 0,
            'self' => new stdClass(),
            'others' => array()
        );

        if (empty($rates)) {
            return $data;
        }

        $userIds = array();
        $courseIds = array();
        foreach ($rates as $r) {
            $userIds[] = $r->user_id;
            $courseIds[] = $r->course_id;
        }
        $userIdsStr = implode(',', $userIds);
        $courseIdsStr = implode(',', $courseIds);

        //获取用户昵称
        $names = $uddb->getResults("SELECT `user_id`, `nickname`, `avatar` FROM `user_social_info` WHERE `user_id` IN ({$userIdsStr})");
        $nicknames = array();
        $avatars = array();
        foreach ($names as $name) {
            $nicknames[$name->user_id] = empty($name->nickname) ? '匿名' : $name->nickname;
            $avatars[$name->user_id] = empty($name->avatar) ? '' : $name->avatar;
        }

        //获取课程名称
        $names = $cmsdb->getResults("SELECT `id`, `course_name` FROM `data_live_course` WHERE `id` IN ({$courseIdsStr})");
        $courseNames = array();
        foreach ($names as $name) {
            $courseNames[$name->id] = empty($name->course_name) ? '查询不到课程名' : $name->course_name;
        }

        foreach ($rates as $rate) {
            if (!$rate->available)
                continue;

            //其他人的评论
            $data['others'][] = array(
                'id' => intval($rate->id),
                'nickname' => $nicknames[$rate->user_id],
                'avatar' => $avatars[$rate->user_id],
                'score' => intval($rate->grade_score),
                'comment' => empty($rate->comment) ? '' : $rate->comment,
                'rate_time' => $rate->grade_time,
                'course_name' => $courseNames[$rate->course_id],
                'course_id' => intval($rate->course_id),
                'is_open' => $rate->is_openclass ? true : false
            );
        }

        return $data;
    }

    /**
     * 根据课堂id获取评价信息
     *
     * @param $classId
     * @param $userId
     * @param int $page
     * @return array
     */
    private function getRateByClass($classId, $userId, $page = 1) {
        global $cmsdb, $uddb;

        $offset = ($page - 1) * self::PERPAGE_COUNT;

        $sql = "SELECT `id`, `user_id`, `grade_score`, `grade_time`, `comment`, `available` FROM `data_liveclass_grade`
        WHERE `class_id`={$classId} AND `user_id`!={$userId} AND `grade_score`!=0 AND `available`=1
        ORDER BY `id` DESC LIMIT {$offset}, ".self::PERPAGE_COUNT;
        $rates = $cmsdb->getResults($sql);

        $sql = "SELECT `id`, `grade_score`, `grade_time`, `comment` FROM `data_liveclass_grade`
        WHERE `user_id`={$userId} AND `class_id`={$classId} LIMIT 1";
        $watched = $cmsdb->getRow($sql);

        $selfStatus = 0;
        $self = new stdClass();
        if (!empty($watched)) {
            $selfStatus = 1;
            if ($watched->grade_score != '0') {
                $u = $uddb->getRow('SELECT `nickname`, `avatar` FROM `user_social_info` WHERE `user_id`=:uid', array(':uid' => $userId));

                $selfStatus = 2;
                $self = array(
                    'id' => intval($watched->id),
                    'score' => intval($watched->grade_score),
                    'avatar' => empty($u->avatar) ? '' : $u->avatar,
                    'nickname' => empty($u->nickname) ? '匿名' : $u->nickname,
                    'comment' => empty($watched->comment) ? '' : $watched->comment,
                    'rate_time' => $watched->grade_time
                );
            }
        }

        $data = array(
            'status' => $selfStatus,  //status字段: 0代表未看过,1代表看过未评价过,2代表评价过
            'self' => $self,
            'others' => array()
        );

        if (empty($rates)) {
            return $data;
        }

        $ids = array();
        foreach ($rates as $r) {
            $ids[] = $r->user_id;
        }
        $idsStr = implode(',', $ids);

        //获取用户昵称
        $names = $uddb->getResults("SELECT `user_id`, `nickname`, `avatar` FROM `user_social_info` WHERE `user_id` IN ({$idsStr})");
        $nicknames = array();
        $avatars = array();
        foreach ($names as $name) {
            $nicknames[$name->user_id] = empty($name->nickname) ? '匿名' : $name->nickname;
            $avatars[$name->user_id] = empty($name->avatar) ? '' : $name->avatar;
        }

        foreach ($rates as $rate) {
            if (!$rate->available)
                continue;

            //其他人的评论
            $data['others'][] = array(
                'id' => intval($rate->id),
                'nickname' => $nicknames[$rate->user_id],
                'avatar' => $avatars[$rate->user_id],
                'score' => intval($rate->grade_score),
                'comment' => empty($rate->comment) ? '' : $rate->comment,
                'rate_time' => $rate->grade_time
            );
        }

        return $data;
    }
}